package logic

import (
	"context"
	"encoding/json"
	"strconv"
	"time"
	"zc1/model/mysql"
	"zc1/model/redis"

	"zc1/userrpc/internal/svc"
	"zc1/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListGoodsLogic {
	return &ListGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListGoodsLogic) ListGoods(in *userrpc.ListGoodsRequest) (*userrpc.ListGoodsResponse, error) {
	// todo: add your logic here and delete this line
	redis.Client.Get("list")
	page := in.Page
	if page <= 0 {
		page = 1
	}
	size := in.Size
	switch {
	case size > 100:
		size = 100
	case size <= 0:
		size = 10
	}
	offset := (page - 1) * size
	var product []mysql.Product

	get := redis.Client.Get("list" + strconv.Itoa(int(offset)) + strconv.Itoa(int(in.Userid)))
	if get.Val() == "" {
		mysql.DB.Where("user_id = ?", in.Userid).Where("name like ?", "%"+in.Name+"%").Order("price desc").Order("created_at desc").Offset(int(offset)).Limit(int(size)).Find(&product)
		marshal, _ := json.Marshal(&product)
		redis.Client.Set("list"+strconv.Itoa(int(offset))+strconv.Itoa(int(in.Userid)), marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &product)
	}

	var products []*userrpc.GoodsList
	for _, m := range product {
		list := userrpc.GoodsList{
			Name:   m.Name,
			Price:  int64(m.Price),
			Money:  int64(m.Money),
			Img:    m.Img,
			Userid: int64(m.UserId),
		}
		products = append(products, &list)
	}
	return &userrpc.ListGoodsResponse{List: products}, nil
}
